#include "head.h"
int main(int argc,char *argv[]){
    //./server 172.22.123.229 1234 4
    ARGS_CHECK(argc,4);
    int workerNum = atoi(argv[3]);
    threadPool_t threadPool;
    threadPoolInit(&threadPool,workerNum);
    int sockFd;
    makeWorker(&threadPool);
    tcpInit(argv[1],argv[2],&sockFd);
    task_t *pTask = (task_t *)calloc(1,sizeof(task_t));
    //bzero(pTask,sizeof(task_t));
    strcpy(pTask->salt,"$6$uw4F3Kne$");//神秘固定盐值

    int firstFd = accept(sockFd,NULL,NULL);
    //接收token，如果是第一次connect token为0
    printf("netFd=%d\n",firstFd);
    recv(firstFd,pTask->token,98,0);
    printf("token = %s\n",pTask->token);
    if(strlen(pTask->token)==0){
        //登录时用户名与固定盐值制作一个token
        char token[100]={0};
        strcpy(token,crypt("chao",pTask->salt));
        puts("-----first login-----");
        //发给客户端token
        send(firstFd,token,98,0);
    }

    //开始epoll监听
    int epfd = epoll_create(10);
    epollAdd(sockFd,epfd);
    epollAdd(firstFd,epfd);
    struct epoll_event readyList[2];
    while (1)
    {
        int readyNum = epoll_wait(epfd,readyList,2,-1);
        puts("epoll ready");
        for(int i =0;i<readyNum;i++){
            if(readyList[i].data.fd == sockFd){
                int netFd = accept(sockFd,NULL,NULL);
                //接收token，如果是第一次connect token为0
                printf("netFd=%d\n",netFd);
                recv(netFd,pTask->token,98,0);
                printf("token = %s\n",pTask->token);
                if(strlen(pTask->token)!=0){
                    //事件队列是共享资源，需要加锁保护
                    pthread_mutex_lock(&threadPool.mutex);
                    enQueue(&threadPool.taskQueue,netFd);
                    puts("new Task");
                    pthread_cond_signal(&threadPool.cond);
                    pthread_mutex_unlock(&threadPool.mutex);
                }
            }
            if(readyList[i].data.fd == firstFd){
                puts("欢迎来到短命令");
                task_t mypTask = *pTask; //接收下来
                mypTask.netFd=firstFd;
                bzero(mypTask.buf,sizeof(mypTask.buf));
                int ret = recv(mypTask.netFd,mypTask.buf,sizeof(mypTask.buf),0);
                if(ret == 0){
                    puts("对面客户端断开！");
                    break;
                }
                sOrderJudge(&mypTask);
            }
        }
    }
}